#!/usr/bin/env python3
import requests
import json
import argparse

class CacheClient:
    def __init__(self, base_url):
        self.base_url = base_url.rstrip('/')
    
    def set(self, key, value):
        """设置缓存值"""
        data = {key: value}
        response = requests.post(self.base_url, json=data)
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Error: {response.status_code}")
    
    def get(self, key):
        """获取缓存值"""
        response = requests.get(f"{self.base_url}/{key}")
        if response.status_code == 200:
            return response.json()
        elif response.status_code == 404:
            return None
        else:
            raise Exception(f"Error: {response.status_code}")
    
    def delete(self, key):
        """删除缓存值"""
        response = requests.delete(f"{self.base_url}/{key}")
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Error: {response.status_code}")

def main():
    parser = argparse.ArgumentParser(description='Distributed Cache Client')
    parser.add_argument('--server', default='http://127.0.0.1:9527', 
                       help='Cache server URL (default: http://127.0.0.1:9527)')
    
    args = parser.parse_args()
    client = CacheClient(args.server)
    
    print(f"连接到缓存服务器: {args.server}")
    print("可用命令: set <key> <value> | get <key> | delete <key> | exit")
    
    while True:
        try:
            command = input("> ").strip()
            if not command:
                continue
            
            parts = command.split()
            cmd = parts[0].lower()
            
            if cmd == 'exit':
                break
            elif cmd == 'set' and len(parts) >= 3:
                key = parts[1]
                value = ' '.join(parts[2:])
                try:
                    result = client.set(key, value)
                    print(f"已设置: {result}")
                except Exception as e:
                    print(f"错误: {e}")
            elif cmd == 'get' and len(parts) == 2:
                key = parts[1]
                try:
                    result = client.get(key)
                    if result:
                        print(f"获取结果: {result}")
                    else:
                        print("键不存在")
                except Exception as e:
                    print(f"错误: {e}")
            elif cmd == 'delete' and len(parts) == 2:
                key = parts[1]
                try:
                    result = client.delete(key)
                    print(f"删除结果: {result}")
                except Exception as e:
                    print(f"错误: {e}")
            else:
                print("无效命令")
                
        except KeyboardInterrupt:
            print("\n退出客户端")
            break
        except Exception as e:
            print(f"错误: {e}")

if __name__ == '__main__':
    main()
